package com.everflourish.yeah100.act.statistics;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseFragment;
import com.everflourish.yeah100.adapter.FragmentTeacherErrorAdapter;
import com.everflourish.yeah100.entity.statistics.ObjectiveTopic;
import com.everflourish.yeah100.http.ExaminationRequest;
import com.everflourish.yeah100.ui.MyHScrollView;
import com.everflourish.yeah100.utils.LogUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.collections.FailureRateCollections;
import com.everflourish.yeah100.utils.constant.Constant;
import com.everflourish.yeah100.utils.constant.PaperType;
import com.everflourish.yeah100.utils.constant.ResultCode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 作者：Created by liqisi on 2016/7/6.
 * 时间：2016/7/6
 */
public class FragmentTeacherError extends BaseFragment {

    private RecyclerView mRecycleList;
    public FragmentTeacherErrorAdapter mAdapter;
    private ExaminationRequest mRequest;
    public List<ObjectiveTopic> mList;
    private List<MyHScrollView> myHScrollViews;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    public SwipeRefreshLayout.OnRefreshListener mRefreshListener;
    private TextView mEmptyTv;
    private TeacherStatisticsActivity mActivity;
    private boolean isPrepared;  //  标志位，标志已经初始化完成。

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_teacher_error, container, false);
        isPrepared = true;
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        lazyLoad();
    }

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        initData();
        initFragment();
        configWidget();
        isPrepared = false;
    }

    private void initData() {
        mActivity = (TeacherStatisticsActivity) getActivity();
        mRequest = ExaminationRequest.getInstance();
        myHScrollViews = new ArrayList<MyHScrollView>();
        mList = new ArrayList<ObjectiveTopic>();
        mAdapter = new FragmentTeacherErrorAdapter(mContext, myHScrollViews, mList);
    }

    private void initFragment() {
        mRecycleList = (RecyclerView) getView().findViewById(R.id.statistics_teacher_error_rv);
        mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.statistics_teacher_error_swipe);
        mEmptyTv = (TextView) getView().findViewById(R.id.statistics_t_error_empty_tv);
        MyHScrollView myHScrollView = (MyHScrollView) getView().findViewById(
                R.id.statistics_t_error_title_mhv);
        myHScrollViews.add(myHScrollView);
        myHScrollView.setMyHScrollViews(myHScrollViews);
    }

    @SuppressWarnings("ResourceType")
    private void configWidget() {
        mRecycleList.setAdapter(mAdapter);
        mRecycleList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRefreshListener = new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                failureRateObjectStatisticRequest();
            }
        };
        mSwipeRefreshLayout.setColorScheme(R.color.statistics_appbar_primary);
        mSwipeRefreshLayout.setOnRefreshListener(mRefreshListener);
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        mRefreshListener.onRefresh();
    }

    /**
     * 获取客观题错误率信息请求
     */
    private void failureRateObjectStatisticRequest() {
        JsonObjectRequest request = mRequest.tFailureRateObjectRequest(
                mActivity.mExamination.getId(), null, PaperType.NONE,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        failureRateObjectStatisticListener(response);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        mRequest.disposeError(mContext, mLoadDialog, error, "获取题目分析失败");
                    }
                });
        mQueue.add(request);
    }

    /**
     * 获取客观题错误率信息监听
     *
     * @param response
     */
    private void failureRateObjectStatisticListener(JSONObject response) {
        try {
            String resultCode = response.getString(Constant.RESULT_CODE);
            if (resultCode.equals(ResultCode.result_ok.resultCode)) {
                JSONArray jsonArray = response
                        .getJSONArray(Constant.OBJ_FAILURE_RATIO_INFOS);
                Gson gson = new Gson();
                Type type = new TypeToken<List<ObjectiveTopic>>() {
                }.getType();
                List<ObjectiveTopic> objectiveTopics = gson.fromJson(
                        jsonArray.toString(), type);
                if (objectiveTopics == null || objectiveTopics.size() == 0) {
                    // 获取错误率为空
//                    MyToast.showShort(mContext, "没有找到相关的错误率");
                    mEmptyTv.setVisibility(View.VISIBLE);
                } else {
                    mEmptyTv.setVisibility(View.GONE);
                    mList.clear();
                    mList.addAll(objectiveTopics);
                    topicNoSort();
                }
            } else if (resultCode.equals(ResultCode.result_000012E.resultCode)) {
                MyToast.showShort(mContext, R.string.examination_08061_000012E);
            } else if (resultCode.equals(ResultCode.result_300001E.resultCode)) {
                MyToast.showShort(mContext, R.string.examination_08062_300001E);
            } else if (resultCode.equals(ResultCode.result_system_exception_999999E)) {
                MyToast.showShort(mContext, R.string.examination_080699_999999E);
            } else {
                MyToast.showShort(mContext, "获取题目分析失败");
            }
        } catch (Exception e) {
            LogUtil.e("json异常", e);
            MyToast.showShort(mContext, "获取题目分析失败");
        } finally {
            mSwipeRefreshLayout.post(new Runnable() {
                @Override
                public void run() {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            });
        }
    }

    /**
     * 根据题号排序
     */
    private void topicNoSort() {
        Collections.sort(mList, new FailureRateCollections(false,
                FailureRateCollections.COMPARE_TOPIC_NO));
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mQueue.stop();
    }
}